using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Vin.Tool.Attributes;
using Vin.Tool.Core.AssemblyCategory;

namespace Vin.DependencyInjection.Core.Extension;

public static class HostServiceExtension
{
    public static void AddHostService(this IServiceCollection serviceCollection)
    {
        var hostedServices = AssemblyTool.GetTypes<IHostedService>(true);
        // var hostedLifecycleService = AssemblyTool.GetTypes<IHostedLifecycleService>();
        // var backgroundServices = AssemblyTool.GetTypes<BackgroundService>();
        // var allTypes = hostedServices.Concat(hostedLifecycleService).Concat(backgroundServices).ToList();

        foreach (var hostedService in hostedServices)
        {
            if (hostedService.IsAbstract || hostedService.IsGenericType) continue;
            // 判断如果包含 IgnoreServiceAttribute 特性则不注册
            if (hostedService.IsDefined(typeof(IgnoreServiceAttribute), true)) continue;
            // 添加到服务容器
            serviceCollection.AddSingleton(typeof(IHostedService), hostedService);
        }
    }
}